package com.dolphin.directive;

import com.dolphin.commons.Constants;
import com.dolphin.commons.StringUtil;
import com.dolphin.forest.HitokotoForest;
import com.dolphin.model.Option;
import com.dolphin.model.Word;
import com.dolphin.service.OptionService;
import com.dolphin.service.WordService;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@TemplateDirective("wordRandom")
@Component
@SuppressWarnings("all")
public class WordRandomDirective extends BaseDirective {
    private static WordService wordService;
    private static OptionService optionService;
    private static HitokotoForest hitokotoForest;

    @Autowired
    public void setWordService(WordService wordService) {
        WordRandomDirective.wordService = wordService;
    }

    @Autowired
    public void setOptionService(OptionService optionService) {
        WordRandomDirective.optionService = optionService;
    }

    public void setExprList(ExprList exprList) {
        super.setExprList(exprList);
    }

    @Autowired
    public void setHitokotoForest(HitokotoForest hitokotoForest) {
        WordRandomDirective.hitokotoForest = hitokotoForest;
    }

    @Override
    public void exec(Env env, Scope scope, Writer writer) {
        Option option = optionService.getOptionByKey(Constants.OPTION_WEB_WORD_OR_API);
        if (option != null && "1".equals(option.getOptionValue())) {
            Option option2 = optionService.getOptionByKey(Constants.OPTION_WEB_WORD_API);
            try {
                String hitokoto = hitokotoForest.getHitokoto(option2.getOptionValue());
                if (StringUtil.isNotEmpty(hitokoto)) {
                    write(writer, hitokoto);
                } else {
                    write(writer, "api得不到数据，请检查api");
                }
            } catch (Exception e) {
                write(writer, "api请求报错，请检查api");
            }
        } else {
            Word word = wordService.getWordRandom(1);
            if (word == null){
                write(writer, "去后台维护美句或者选择api获取句子方式");
            }else {
                write(writer, word.getText());
            }
        }
    }

}
